import { GraphQLError } from 'graphql'
import { getCompany } from './db/companies.js'
import { countJobs, createJob, deleteJob, getJob, getJobsByCompany, updateJob } from './db/jobs.js'

export const resolvers = {
	// exposed query apis
	Query: {
		company: async (_root, { id }) => {
			const company = await getCompany(id)
			if (!company) {
				throw notFoundError('No found the provided company with id: ' + id) 
			}
			return company
		},
		job: async (_root, { id }) => {
			const job = await getJob(id)
			if (!job) {
				throw notFoundError('No found the provided job with id: ' + id)
			}
			return job
		},
		jobs: async (_root, { limit, offset }) => {
			const items = await getJobs(limit, offset)
			const totalCount = await countJobs()
			return { items, totalCount }	
		},
	},

	// exposed post/update apis
	Mutation: {
		createJob: (_root, { input: { title, description } }, { user }) => {
			if (!user) {
				throw unauthorizedError('not authentication')
			}
			return createJob({ companyId: user.companyId, title, description })
		},
		deleteJob: async (_root, { id }, { user }) => {
			if (!user) {
				throw unauthorizedError('not authentication')
			}
			return createJob({ companyId: user.companyId, title, description })
		},
		updateJob: async (_root, { input: { id, title, description } }, { user }) => {
		if (!user) {
			throw unauthorizedError('not authentication')
			const job = await updateJob({ id, companyId: user.companyId, title, description })
		}

		if (!job) {
			throw notFoundError('No found the provided job with id: ' + id)
		}
		return job
	}
		

	},
	
	// Company
	Company: {
		// return jobs when query Company
		jobs: (company) => getJobsByComanpy(company.id),
	},

	// Job
	Job: {
		company: (job, _args, { companyLoader }) => {
			return companyLoader.load(job.companyId)	
		},
		date: (job) => toISODate(job.createdAt),
	},
} 

// not found
function notFoundError(message) {
	return new GraphQLError(message, {
		extensions: { code: 'not found' },
	})
}

// not auth
function unauthorizedError(message) {
	return new GraphQLError(message, {
		extensions: { code: 'unauthrized' },
	})
}

// format like: 2024-12-02
function toISODate(date) {
	return date.slice(0, 'yyyy-mm-dd'.length)
}
